package com.bubbo.rpc.client.util;

import com.bubbo.rpc.client.util.serialize.Serializer;
import com.bubbo.rpc.client.util.serialize.impl.ProtostuffSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by waasdasd on 2017/3/31.
 */
public class Decoder extends ByteToMessageDecoder {
    private Class<?> genericClass;

    private Serializer serializer;

    public Decoder(Class<?> genericClass) {
        this.genericClass = genericClass;
        this.serializer = new ProtostuffSerializer();
    }


    public Decoder(Class<?> genericClass,Serializer serializer) {
        this.genericClass = genericClass;
        if(serializer==null){
            this.serializer = new ProtostuffSerializer();
        }
        this.serializer = serializer;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);

        out.add(serializer.deserialize(data, genericClass));
    }

}
